<template>
  <view class="widget-calendar">
    <view
      class="widget-calendar font-songti text-sm d-flex flex-align-center"
      @click="open"
      >{{ date }}<text class="ml-5 iconfont icon-xiangxia2"></text
    ></view>
    <root-portal>
      <uni-popup
        ref="popup"
        type="center"
      >
        <view class="widget-calendar-body">
          <uni-calendar
            class="uni-calendar--hook"
            :lunar="true"
            :selected="info.selected"
            :showMonth="false"
            @change="change"
            @monthSwitch="monthSwitch"
          />

          <view class="d-flex flex-justify-between p-20 pb-40">
            <button
              class="btn btn-default"
              @click="close"
            >
              <text class="font-songti">取消</text>
            </button>
            <button
              class="btn btn-primary"
              @click="onSubmit"
            >
              <text class="font-songti">确定</text>
            </button>
          </view>
        </view>
      </uni-popup>
    </root-portal>
  </view>
</template>

<script>
  import moment from "moment";
  export default {
    props: {
      value: {
        type: String,
        default: "",
      },
      visible: {
        type: Boolean,
        default: false,
      },
    },
    data() {
      return {
        date: "",
        info: {
          lunar: true,
          range: true,
          insert: false,
          selected: "",
        },
      };
    },
    watch: {
      value(newValue) {
        this.date = newValue;
      },
      visible(newValue) {
        if (newValue) {
          this.$refs.popup.open();
          this.$emit("open");
        } else {
          this.$emit("close");
          this.$refs.popup.close();
        }
      },
    },
    mounted() {
      this.date = this.value || moment().format("YYYY-MM-DD");
      this.info.selected = this.date;
      if (this.visible) {
        this.$emit("open");
        this.$refs.popup.open();
      }
    },

    methods: {
      open() {
        this.$refs.popup.open();
        this.$emit("open");
      },
      close() {
        this.$refs.popup.close();
        this.$emit("close");
      },
      change(e) {
        this.info.selected = e.fulldate;
      },

      monthSwitch(e) {
        console.log("monthSwitchs 返回:", e);
      },

      onSubmit() {
        this.date = this.info.selected;
        this.$emit("change", this.info.selected);
        this.$emit("input", this.info.selected);
        this.$refs.popup.close();
        this.$emit("update:visible", this.info.selected);
        this.$emit("close");
      },
    },
  };
</script>

<style lang="scss">
  .widget {
    &-calendar {
      display: inline-flex;

      &-body {
        background-color: #fff;
        overflow: hidden;
        border-radius: 20rpx;
      }
    }
  }
</style>
